#averagePropsToFile.py
#
#Given proportions for namespaces, offset year, and cohort, write a file that can be read by R to create graphs
import sys
import collections
import os

def realMain():
	intNs = ["main", "talk", "user", "user talk", "project"]
	path1 = sys.argv[1]
	path2 = "/scratch/wikipedia/statistics/hour_averages_nomodel/FINAL.txt"
	path3 = sys.argv[2]

	if os.path.isfile(path3+"proportions.R"):
		os.remove(path3+"proportions.R")
	global f3
	f3 = open(path3+"proportions.R", "a+")



	for ns in intNs:
		mmList = findmm(path1, path2, ns)
		[minimum, maximum] = mmList
		main(path1, ns, minimum, maximum)
		print mmList
		main(path2, ns, minimum, maximum)

def main(thing1, thing2, minimum, maximum):
	
	colorList = ["blue","red","orange","goldenrod4","black","green","coral","violet","skyblue","aquamarine4","blue"]
	years = ["2003","2004","2005","2006","2007","2008","2009","2010","2011","2012"]
	yearList = []
	for x in range(0,len(years)):
		newList = "years"+str(x)
		newList = years[x:]
		yearList.append(newList)

	syaverages = thing1
	#totalaverages = sys.argv[2]
	namespace = thing2
	

	if "hour" in syaverages:
		title = "Average Proportion of Time Spent on "
		unit = "Time"
	elif "edit" in syaverages:
		title = "Average Proportion of Edits in "
		unit = "Edits"
		

	filetitle = namespace+unit

	tList = []
	yearDict = collections.defaultdict(list)
		
	#for x in range(2003,2013):
	#	for y in range(0,x-2003):
	#		yearDict[str(x)].append('0')
	
	f = open(syaverages, "r")
	
	for line in f:
		tokens = line.split("\t")
		if ((namespace in tokens[0] and "talk" not in namespace and "talk" not in tokens[0]) or ("talk" in namespace and namespace in tokens[0] and namespace <> "talk") or ("talk" == namespace and "talk" == tokens[0][4:-1])) and "2" in tokens[0]: 
			year = tokens[0][:4]
			percent = tokens[1].replace('\n','')
			yearDict[year].append(percent)

	
	namespaceTitle = namespace[0].upper()+namespace[1:]	
	namespace = namespace.replace(' ','')

	for key in sorted(yearDict.keys()):
		aList = yearDict[key]
		f3.write(namespace + key + " <- c(" + ",".join(aList) + ')\n')

	#print namespace + "total" + " <- c(" + ",".join(tList) + ')'
	
	num = 0
	for years in yearList:		
		f3.write("years" + str(num) + " <- c(" + ",".join(years) + ')\n')
		num += 1

	f3.write('jpeg("'+filetitle+'.jpeg", width=500, height=500, units = "px",res="72",quality="100")\n')
	f3.write('plot(years0, ' +namespace + "2003" + ', type="o", main="' + title + namespaceTitle + '",xlab="Year",ylab="Proportion of '+unit+'",col="blue",ylim=c('+str(minimum)+','+str(maximum+.02)+'))\n')
	y = 0
	for x in sorted(yearDict.keys()):			
		f3.write("lines(years"+str(y)+", " + namespace+str(x)+',type="o",col="'+colorList[y]+'")\n')
		y += 1
	f3.write('legend("topleft",legend=c("2003","2004","2005","2006","2007","2008","2009","2010","2011","2012"),text.col=c("blue","red","orange","goldenrod4","black","green","coral","violet","skyblue","aquamarine4"), horiz = "TRUE", text.width = .425, bty = "n")\n')	
	f3.write("dev.off()\n")
	

def findmm(path1, path2, namespace):

	minimum = 10
	maximum = 0

	f1 = open(path1, "r")
	
	for line in f1:
		tokens = line.split("\t")
		if ((namespace in tokens[0] and "talk" not in namespace and "talk" not in tokens[0]) or ("talk" in namespace and namespace in tokens[0] and namespace <> "talk") or ("talk" == namespace and "talk" == tokens[0][4:-1])) and "2" in tokens[0]: 
			year = tokens[0][-5:-1]
			percent = tokens[1].replace('\n','')
			if float(percent) > maximum:
				maximum = float(percent)
			if float(percent) < minimum:
				minimum = float(percent)

	f2 = open(path2, "r")

	for line in f2:
		tokens = line.split("\t")
		if ((namespace in tokens[0] and "talk" not in namespace and "talk" not in tokens[0]) or ("talk" in namespace and namespace in tokens[0] and namespace <> "talk") or ("talk" == namespace and "talk" == tokens[0][4:-1])) and "2" in tokens[0]: 
			year = tokens[0][-5:-1]
			percent = tokens[1].replace('\n','')
			if float(percent) > maximum:
				maximum = float(percent)
			if float(percent) < minimum:
				minimum = float(percent)

	return [minimum, maximum]

realMain()
